package com.krautzlabs;

import java.io.IOException;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;

import android.content.Context;
import android.graphics.Canvas;
import android.util.Log;
import android.view.SurfaceHolder;

public class Main extends Thread{
		
		private Context context; //need to get resources from
		private SurfaceHolder surfaceHolder;
		private MapView mapView;
		
		private GameState gameState;
		private boolean isRunning;
		
		//game loop variables
		private final static int MAX_FPS = 50;
		private final static int MAX_FRAMES_SKIPS = 5;
		private final static int FRAME_PERIOD = 1000/MAX_FPS;
	
		public Main(Context context, SurfaceHolder surfaceHolder, MapView mapView)
		{
			this.isRunning = false;
			
			this.context = context;
			this.surfaceHolder = surfaceHolder;
			this.mapView = mapView;
			
			this.gameState = new GameState();
			parseMapFile();
			
		}
		
		public void run()
		{
			Canvas canvas;
			
			while(isRunning)
			{
				canvas = null;
				try{
					canvas = this.surfaceHolder.lockCanvas();
					synchronized(surfaceHolder) {
						
						this.mapView.onDraw(canvas);
					}
					
				}
				finally{
					if(canvas != null) {
						surfaceHolder.unlockCanvasAndPost(canvas);
					}
						
				}
				
			}
		}
		
		public void setRunning(boolean run)
	    {
	            this.isRunning = run;
	    }
		
		
		
		
		//doesnt belong here...will move later
		private void parseMapFile()
		{
			try {
				SAXParserFactory spf = SAXParserFactory.newInstance();
				SAXParser sp = spf.newSAXParser();
				XMLReader xr = sp.getXMLReader();
				
				//mapreader parses the xml and creates appropriate objects
				MapReader mapReader = new MapReader(this.gameState);
				xr.setContentHandler(mapReader);
				//R.raw.map will have to be dynamic once we have a map chooser activity
				if(context == null)
					Log.d("xml", "context is NULL");
				xr.parse(new InputSource(context.getResources().openRawResource(R.raw.map)));
			} catch (ParserConfigurationException e) {
				e.printStackTrace();
			} catch (SAXException e) {
				e.printStackTrace();
			} catch(IOException e) {
				e.printStackTrace();
			}
		}
		
		public GameState getGameState()
		{
			return this.gameState;
		}
}
